<template>
  <div>
    <div id="container"></div>
    <AddRoadLinkPanel 
      v-if="isDataReady"
      class="panel"
      @addLink="init"
      @selectLink="selectLink"
      :roadbook-id="curRoadbookInfo.id"
      :roadbook-name="curRoadbookInfo.name"
    />
    <div class="searchpanel">
      <SearchPanel @chooseLocation="chooseLocation"></SearchPanel>
      <PointerEditPanel 
        class="linkshowpanel" 
        :curLink="curLinkInfo" 
        :newNode="selectNode"
        @showLink="showLink"
        />
    </div>
    <StyleSelect class="StyleSelectPanel" @selectMapStyle="onStyleChange"></StyleSelect>
  </div>
  
</template>

<script setup name="Edit">
import { onMounted, onUnmounted,ref } from "vue";
import ICON from "@/assets/icons";
import AMapLoader from "@amap/amap-jsapi-loader";
import amapConfig from "@/mapConfig";
import {generateMarkerContent} from "@/utils/amap/MyMapLib";

//引入API
import { listNodes, getNodes, delNodes, addNodes, updateNodes } from "@/api/work/nodes"
import { listRoadbooks, getRoadbooks, delRoadbooks, addRoadbooks, updateRoadbooks } from "@/api/work/roadbooks"
import { listRoadlinks, getRoadlinks, delRoadlinks, addRoadlinks, updateRoadlinks } from "@/api/work/roadlinks"
//引入自定义组件
import AddRoadLinkPanel from "../../../components/Amap/AddRoadLinkPanel.vue";
import ShowRoadLinkPanel from "../../../components/Amap/ShowRoadLinkPanel.vue";
import SearchPanel from "../../../components/Amap/SearchPanel.vue";
import PointerEditPanel from "../../../components/Amap/PointerEditPanel.vue";
import StyleSelect from "../../../components/Amap/StyleSelect.vue"
const isDataReady = ref(false)
//获取路由参数
import { useRoute } from 'vue-router'
const route = useRoute()
const roadbookId = route.query.id
const mapstyle = amapConfig.mapstyle
//已加载数据
const curRoadbookInfo = ref({})
const curLinkInfo = ref({})
const Roadlinks = ref([])
const nodes = ref([])
//正在创建数据
const croadlink=ref({
  parentId: roadbookId,
  parentName: null,
  name: null,
  note: null,
  method: null,
  roadtype: null,
  predicteTime: null,
  thumbnail: null,
  other: null
})
const node=ref({})
const selectNode = ref({})
const isNoLinks = ref(false)

let map = null;
// 存储所有标记的引用
const markers = ref([]);

/** 获取初始化数据 */
async function init(){
  let roadbooksinfo = await getRoadbooks(roadbookId)  //获取当前路书数据
  curRoadbookInfo.value = roadbooksinfo.data
  isDataReady.value = true
  //console.log(curRoadbookInfo.value)
  let roadlist = await listRoadlinks({
    //获取线路列表
    pageNum: 1,
    pageSize: 10,
    parentId: curRoadbookInfo.value.id,
  })
  Roadlinks.value = roadlist.rows
  if(Roadlinks.value.length > 0 && isNoLinks.value == false){
    curLinkInfo.value = Roadlinks.value[0]
    isNoLinks.value = true
  }
}
/** 选择路线 */
function selectLink(row){
  curLinkInfo.value = row
}
/** 选择点位 */
const marker = ref({});
function chooseLocation(location){
  selectNode.value = location
  if(marker.value != null){
    map.remove(marker.value); //清除 marker
  }
  
  marker.value = new AMap.Marker({
    position: new AMap.LngLat(location.location[0], location.location[1]), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
    title: location.keyword,
    draggable: true, // 启用拖动
  });
  
  // 添加拖动事件监听
  marker.value.on('dragend', function(e) {
    const newPosition = e.lnglat;
    selectNode.value.location = [newPosition.lng, newPosition.lat];
    selectNode.value.position = `${newPosition.lng},${newPosition.lat}`;
    console.log('标记拖动到新位置:', selectNode.value.position);
  });
  
  map.add(marker.value)
  map.setCenter(location.location)
}

// 创建右键菜单
let contextMenu = null;

/** 加载地图及配置 */
onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: amapConfig.amap_security,
  };
  AMapLoader.load({
    key: amapConfig.amap_key, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale",'AMap.Driving','AMap.DragRoute'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
  .then((AMap) => {
    map = new AMap.Map("container", {
      // 设置地图容器id
      viewMode: "3D", // 是否为3D地图模式
      zoom: 11, // 初始化地图级别
      center: [116.397428, 39.90923], // 初始化地图中心点位置
    });
    contextMenu = new AMap.ContextMenu();
    //右键放大
    contextMenu.addItem("放大一级", function () {
        map.zoomIn();
    }, 0);

    map.on("rightclick", function (ev) {
      //触发事件的对象
      var target = ev.target;
      //触发事件的地理坐标，AMap.LngLat 类型
      var lnglat = ev.lnglat;
      //触发事件的像素坐标，AMap.Pixel 类型
      var pixel = ev.pixel;
      //触发事件类型
      var type = ev.type;
      //console.log(target,type,lnglat,pixel)
      contextMenu.open(map, lnglat);
    });
  })
  .catch((e) => {
    console.log(e);
  });
});

/** 展示路线 */
function showLink(nodes){
  nodesDataDeal(nodes)
  console.log(nodes[0])
  switch(2){
    case 1:
      AMap.plugin("AMap.Driving", function () {
        var driving = new AMap.Driving({
          policy: 0, //驾车路线规划策略，0是速度优先的策略
          map: map,
          //panel 指定将结构化的路线详情数据显示的对应的 DOM 上，传入值需是 DOM 的 ID
          //panel: "container",
        });
        var startLngLat = nodes[0].position; //起始点坐标
        var endLngLat = nodes[nodes.length-1].position; //终点坐标
        var opts = {
          waypoints: [], //途经点参数，最多支持传入16个途经点
        };
        for(let i=1;i<nodes.length-1;i++){
          opts.waypoints.push(nodes[i].position)
        }

        driving.search(startLngLat, endLngLat, opts, function (status, result) {
          //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
          //查询成功时，result 即为对应的驾车导航信息
          console.log(status,result)
        });
      });
      break;
    case 2:
      let path = []
      for(let i in nodes){
        if(nodes[i].isPath === "Y"){
          path.push(nodes[i].position)
        }
      }
      AMap.plugin("AMap.Driving", function () {
        var currentDragRouting = new AMap.DragRoute(map, path, 0, {
          startMarkerOptions: {
            offset: new AMap.Pixel(-13, -43),
            icon: new AMap.Icon({ // 设置途经点的图标
                size: new AMap.Size(26, 43),
                image: ICON.start,
                // imageOffset: new AMap.Pixel(0,0), // 图片的偏移量，在大图中取小图的时候有用
                imageSize: new AMap.Size(26, 43) // 指定图标的大小，可以压缩图片

            }),
          },
            endMarkerOptions: {
              offset: new AMap.Pixel(-13, -43),
              icon: new AMap.Icon({ // 设置途经点的图标
                size: new AMap.Size(26, 43),
                image: ICON.end,
                // imageOffset: new AMap.Pixel(0,0), // 图片的偏移量，在大图中取小图的时候有用
                imageSize: new AMap.Size(26, 43) // 指定图标的大小，可以压缩图片
              }),
            },
            midMarkerOptions: {
              offset: new AMap.Pixel(-9, -9),
              icon: new AMap.Icon({ // 设置途经点的图标
                size: new AMap.Size(30, 30),
                image: ICON.midIcon,
                // imageOffset: new AMap.Pixel(0,0), // 图片的偏移量，在大图中取小图的时候有用
                imageSize: new AMap.Size(18, 18) // 指定图标的大小，可以压缩图片
              }),
            },
        })

        // 路线规划完成时
        currentDragRouting.on('complete', res=> {
            // 路线规划完成后，返回的路线数据：设置距离、行驶时间
            let lineData = res.data.routes[0]
            let distance =  (lineData.distance / 1000).toFixed(1) // m -> km
            let time = (lineData.time / 60).toFixed() // second -> min

            //fetchWeatherFromRoute(lineData.steps)

            // if (activeLineObj.value) {
            //     activeLineObj.value.distance = parseFloat(distance)
            //     activeLineObj.value.time = parseInt(time)
            // }

            // drivingInfo.value.distance = distance
            // drivingInfo.value.time = time
        })

        // 查询导航路径并开启拖拽导航
        currentDragRouting.search()
      })
      break;

  }
  loadLineLabels(map, nodes)
  
}
/** 类型变化 */
function onStyleChange(msg){
  map.setMapStyle(msg.style);
}

// 添加路线标记
function loadLineLabels(map, nodes) {
  if (nodes.length <= 0) {
    return
  }
  // 清除现有标记
  clearMarkers();
  
  nodes.forEach((item, index) => {
    addMarker(map, item, index)
  })
}

/** 渲染节点 */
function addMarker(map, item, index) {
  let marker = new AMap.Marker({
    position: item.position,
    title: item.note,
    draggable: true, // 启用拖动
    content: generateMarkerContent(item.nodeName, item.note, item.thumbnail, "blue", index),
  });
  
  // 添加拖动事件监听
  marker.on('dragend', function(e) {
    const newPosition = e.lnglat;
    // 更新节点数据
    item.position = [newPosition.lng, newPosition.lat];
    item.location = `${newPosition.lng},${newPosition.lat}`;
    console.log('标记拖动到新位置:', item.location);
    
    // 如果拖动的是当前选中的节点，更新selectNode
    if (selectNode.value && selectNode.value.id === item.id) {
      selectNode.value.position = item.position;
      selectNode.value.location = item.location;
    }
  });
  
  markers.value.push(marker);
  map.add(marker);
}

// 清除所有标记
function clearMarkers() {
  markers.value.forEach(marker => {
    map.remove(marker);
  });
  markers.value = [];
}

/** nodes数据处理 */
function nodesDataDeal(nodes){
  for(let i in nodes){
    nodes[i].position = [nodes[i].position.split(",")[0],nodes[i].position.split(",")[1]]
  }
  nodes = nodes.sort((a, b) => a.serial - b.serial);
}

onUnmounted(() => {
  map?.destroy();
});

function addRoadLink(){

}

init()
</script>


<style scoped>
#container {
  width: 100%;
  height: 850px;
}
.panel{
  position: absolute;
  z-index: 2;
  width: 380px;
  right: 10px;
  top: 20px;
}
.StyleSelectPanel{
  position: absolute;
  z-index: 2;
  width: 380px;
  right: 10px;
  bottom:40px;
}
.searchpanel{
  position: absolute;
  z-index: 2;
  width: 420px;
  left: 20px;
  top: 20px;

  .linkshowpanel{
    background-color: white;
    padding: 20px;
    margin-top: 10px;
  }
}
.showpanel{
  position: absolute;
  z-index: 2;
  width: 380px;
  left: 20px;
  top: 50px;
}

</style>
<style>
  /* 基础样式变量 */
  :root {
      --bg-light: #f8f9fa;
      --text-main: #333;
      --text-subtitle: #666;
      --border-normal: #dee2e6;
      --color-main: #007bff;
      --blue: #007bff;
      --green: #28a745;
      --red: #dc3545;
      --orange: #fd7e14;
      --yellow: #ffc107;
      --radius: 4px;
  }
  
  body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      padding: 20px;
      background-color: #f5f5f5;
  }
  
  .demo-container {
      max-width: 1000px;
      margin: 0 auto;
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  }
  
  h1 {
      text-align: center;
      color: var(--text-main);
      margin-bottom: 30px;
  }
  
  .markers-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      margin-top: 20px;
  }
  
  /* 标记组件样式 */
  .unselectable {
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
  }
  
  .marker {
      background-color: var(--bg-light);
      border-radius: 10px;
      line-height: 1.3;
      color: var(--text-main);
      transition: all 0.3s;
      box-shadow: 2px 2px 5px rgba(121, 85, 72, 0.39);
      display: flex;
      align-items: stretch;
      justify-content: flex-start;
      flex-flow: column nowrap;
      position: relative;
  }
  
  .marker.no-content {
      border-radius: 10px;
      overflow: hidden;
  }
  
  .marker.no-content .marker-index {
      border-bottom: none;
  }
  
  .marker.no-content .marker-content {
      padding: 0;
  }
  
  .marker:hover {
      z-index: 99999;
      border-radius: 10px;
      transition: all 0.3s;
      transform: scale(1.2);
      transform-origin: center center;
  }
  
  .marker:hover .marker-index .index {
      color: var(--color-main);
      text-shadow: 1px 2px 1px rgba(0, 123, 255, 0.4);
  }
  
  .marker-index {
      border-radius: 10px 10px 0 0;
      border-bottom: 1px solid var(--border-normal);
      background-color: white;
      padding: 5px 10px;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: flex-start;
  }
  
  .marker-index .index {
      margin-right: 10px;
      font-weight: bold;
      color: rgba(0, 0, 0, 0.4);
      font-size: 18px;
  }
  
  .marker-index .title {
      white-space: nowrap;
      font-weight: bold;
      font-size: 15px;
  }
  
  .marker-content {
      padding: 4px 8px 10px;
  }
  
  .marker-content .note {
      white-space: nowrap;
      font-size: 0.7rem;
      color: var(--text-subtitle);
  }
  
  .marker-content .view {
      transition: all 0.3s;
      margin-top: 5px;
      width: 60px;
      border-radius: var(--radius);
      overflow: hidden;
  }
  
  .marker-content .view img {
      display: block;
      width: 100%;
  }
  
  .marker-content .view:hover {
      box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
      transform: scale(5);
      transform-origin: center center;
      margin-top: 10px;
      transition: all 0.3s;
  }
  
  /* 颜色类型样式 */
  .marker.blue .marker-index {
      color: white;
      background-color: var(--blue);
      border-bottom: 1px solid var(--blue);
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
  }
  
  .marker.blue .marker-index .index {
      color: rgba(255, 255, 255, 0.8);
  }
  
  .marker.blue .marker-content {
      border-radius: 0 0 10px 10px;
      background-color: rgba(0, 123, 255, 0.15);
  }
  
  .marker.green .marker-index {
      color: white;
      background-color: var(--green);
      border-bottom: 1px solid var(--green);
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
  }
  
  .marker.green .marker-index .index {
      color: rgba(255, 255, 255, 0.8);
  }
  
  .marker.green .marker-content {
      border-radius: 0 0 10px 10px;
      background-color: rgba(40, 167, 69, 0.15);
  }
  
  .marker.red .marker-index {
      color: white;
      background-color: var(--red);
      border-bottom: 1px solid var(--red);
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
  }
  
  .marker.red .marker-index .index {
      color: rgba(255, 255, 255, 0.8);
  }
  
  .marker.red .marker-content {
      border-radius: 0 0 10px 10px;
      background-color: rgba(220, 53, 69, 0.15);
  }
  
  .marker.orange .marker-index {
      color: white;
      background-color: var(--orange);
      border-bottom: 1px solid var(--orange);
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
  }
  
  .marker.orange .marker-index .index {
      color: rgba(255, 255, 255, 0.8);
  }
  
  .marker.orange .marker-content {
      border-radius: 0 0 10px 10px;
      background-color: rgba(253, 126, 20, 0.15);
  }
  
  .marker.yellow .marker-index {
      color: white;
      background-color: var(--yellow);
      border-bottom: 1px solid var(--yellow);
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
  }
  
  .marker.yellow .marker-index .index {
      color: rgba(255, 255, 255, 0.8);
  }
  
  .marker.yellow .marker-content {
      border-radius: 0 0 10px 10px;
      background-color: rgba(255, 193, 7, 0.15);
  }
  
  .hidden {
      display: none;
  }
</style>
